#include "interpolation.h"
#include "sdl_auxiliary.h"
#include "sdl_screen.h"

#define SCREEN_WIDTH 640
#define SCREEN_HEIGHT 480


Interpolation::Interpolation() throw (sdl::Exception)
: _topLeft(1.f, 0.f, 0.f) // red
, _topRight(0.f, 0.f, 1.f) // blue
, _bottomLeft(1.f, 1.f, 0.f) // yellow
, _bottomRight(0.f, 1.f, 0.f) // green
{
	sdl::Screen* s = sdl::Screen::getInstance();
	s->setCaption("Interpolation");
	// Register callbacks
	s->addListener(this);
	sdl::Event::getInstance()->addListener(this);
	// Update on start
	s->update();
	// Enter main loop
	sdl::Event::getInstance()->wait();
	// Get a screenshot
	s->saveBmp("screenshot.bmp");
}


void Interpolation::on(sdl::SurfaceListener::Update, sdl::Surface* s) throw()
{
	int width = s->getWidth();
	int height = s->getHeight();
	float t;
	glm::vec3 leftCol, rightCol;

	for (int y = 0; y < height; y++) {
		// Interpolate (c0 * (1 - t) + c1 * t)
		t = y / (height - 1.f);
		leftCol = glm::mix(_topLeft, _bottomLeft, t);
		rightCol = glm::mix(_topRight, _bottomRight, t);
		for (int x = 0; x < width; x++) {
			s->putPixel(x, y, glm::mix(leftCol, rightCol, x / (width - 1.f)));
		}
	}
}


void Interpolation::on(sdl::EventListener::NewEvent, const SDL_Event* e) throw()
{
	if (e->type == SDL_QUIT ||
		(e->type == SDL_KEYDOWN && e->key.keysym.sym == SDLK_ESCAPE))
	{
		sdl::Event::getInstance()->stopWaiting();
	}
}


int main()
{
	try {
		// Init SDL library
		sdl::initialize();
		// Create window
		sdl::Screen::getInstance()->setVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT);
		Interpolation();
	}
	catch (sdl::Exception& e) {
		// Get rid off warning (format not a string literal
		// and no format arguments)
		fprintf(stderr, "%s", e.what());
		return 1;
	}
	return 0;
}

